import os
import json
import shutil

from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# from webdriver_manager.firefox import GeckoDriverManager
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
import datetime


DRIVER_PATH = 'D:\software\geckodriver-v0.35.0-win64\geckodriver.exe'
class AutoClick:
    def __init__(self,number=1):
        self.readjson()
        self.number =  number
        # 创建 Service 对象
        service = Service(executable_path=DRIVER_PATH)

        # 创建 WebDriver 实例
        self.driver = webdriver.Firefox(service=service)

        # 假设你已经知道你想要检查的网页的URL
        self.driver.get('http://127.0.0.1:7861/?__theme=dark')
        # 获取并打印网页标题
        print(self.driver.current_url)

        self.driver.switch_to.window(self.driver.current_window_handle)
        # 设置SD


        # 设置VAE
        self.seting('setting_sd_vae','label.svelte-1xsj8nn.container input.border-none.svelte-1xsj8nn',
                    self.data['SD'][0]['VAE'])

        # 设置提示词
        self.seting('txt2img_prompt','textarea.scroll-hide.svelte-1f354aw',self.data['SD'][0]['prompt'])

        # 设置反向提示词
        self.seting('txt2img_neg_prompt_row', 'textarea.scroll-hide.svelte-1f354aw', self.data['SD'][0]['negative_prompt'])

        # 设置采样率
        self.seting('txt2img_sampling', 'input.border-none.svelte-1xsj8nn', self.data['SD'][0]['Sampler'])

        # 设置迭代步数
        self.seting('txt2img_steps', 'input.svelte-1cl284s', self.data['SD'][0]['Steps'])

        # 设置高清修复
        checkbox = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.ID, 'txt2img_hr-visible-checkbox')))
        # 检查复选框是否已被选中，如果没有，则点击它
        if not checkbox.is_selected():
            checkbox.click()

        # 设置附加网络
        # 找到id为"component-615"的div元素
        parent_div = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.ID, 'component-617')))

        # input_element = WebDriverWait(parent_div, 10).until(
        #     EC.element_to_be_clickable((By.CSS_SELECTOR, '.svelte-vt1mxs')))
        #
        #
        #
        # # 检查元素是否可见，如果不可见，则点击使其可见
        # if input_element.is_displayed() == False:
        #     # 这里可能需要一些JavaScript来改变元素的可见性
        #     self.driver.execute_script("arguments[0].style.display = 'block';", input_element)
        #     print('addition 可见')
        parent_div.click()

        parent_div = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.ID, 'component-619')))

        checkbox = WebDriverWait(parent_div, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, 'input.svelte-1ojmf70')))

        # 检查复选框是否已被选中，如果没有，则点击它
        if not checkbox.is_selected():
            checkbox.click()

        # 设置模型及权重 border-none svelte-1xsj8nn svelte-1cl284s
        self.seting('component-624', 'input.border-none.svelte-1xsj8nn', self.data['SD'][0]['model1'])
        self.seting('component-636', 'input.border-none.svelte-1xsj8nn', self.data['SD'][0]['model2'])
        self.seting('component-648', 'input.border-none.svelte-1xsj8nn', self.data['SD'][0]['model3'])
        self.seting('component-660', 'input.border-none.svelte-1xsj8nn', self.data['SD'][0]['model4'])
        self.seting('component-672', 'input.border-none.svelte-1xsj8nn', self.data['SD'][0]['model5'])

        self.seting('component-629', 'input.svelte-1cl284s', self.data['SD'][0]['weight1'])
        self.seting('component-642', 'input.svelte-1cl284s', self.data['SD'][0]['weight2'])
        self.seting('component-654', 'input.svelte-1cl284s', self.data['SD'][0]['weight3'])
        self.seting('component-665', 'input.svelte-1cl284s', self.data['SD'][0]['weight4'])
        self.seting('component-678', 'input.svelte-1cl284s', self.data['SD'][0]['weight5'])



    def readjson(self):
        # 假设你的 JSON 数据存储在名为 data.json 的文件中
        with open('config.json', 'r') as file:
            self.data = json.load(file)

        # 打印整个 JSON 数据
        print(json.dumps(self.data, indent=4))

    def savejson(self):
        # 第一张完成生成后保存！！！
        # 假设原始 JSON 文件的路径
        source_path = 'path/to/your/source_file.json'

        # 指定目标路径
        destination_path = 'path/to/your/destination_file.json'

        # 检查源文件是否存在
        if os.path.exists(source_path):
            # 复制文件
            shutil.copy(source_path, destination_path)
            print(f"文件已从 {source_path} 复制到 {destination_path}")
        else:
            print(f"源文件 {source_path} 不存在。")

    def seting(self,parent,imputclass,data):
        parent_div = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.ID, parent)))
        input_element = WebDriverWait(parent_div, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, imputclass)))
        # 清除文本框中可能存在的任何预先填充的文本
        input_element.clear()
        # 设置文本框的值
        input_element.send_keys(data)
        # 可选：如果你需要在设置值后提交表单，可以发送回车键
        input_element.send_keys(Keys.RETURN)

    def generate(self):
        # 初始化计数器
        click_count = 0
        try:
            while click_count < self.number:
                # 等待“生成”按钮出现并点击
                try:
                    # 等待直到“生成”按钮可点击
                    generate_button = WebDriverWait(self.driver, 10).until(
                        EC.element_to_be_clickable((By.ID, 'txt2img_generate'))
                    )
                    generate_button.click()
                    print("点击了'生成'按钮")

                    # 等待“中止”按钮出现，表示生成已经开始
                    interrupt_button = WebDriverWait(self.driver, 10).until(
                        EC.presence_of_element_located((By.ID, 'txt2img_interrupt'))
                    )
                    print("检测到按钮状态变为'中止'")

                    # 等待“中止”按钮消失，表示生成已完成
                    WebDriverWait(self.driver, 30).until(
                        EC.invisibility_of_element_located((By.ID, 'txt2img_interrupt'))
                    )
                    print("检测到生成已完成，'中止'按钮已消失")

                    # 再次等待“生成”按钮可点击
                    generate_button = WebDriverWait(self.driver, 10).until(
                        EC.element_to_be_clickable((By.ID, 'txt2img_generate'))
                    )
                    print("检测到按钮状态再次变为'生成'")
                    click_count += 1
                    print(f'已生成{click_count}次图片')


                except TimeoutException:
                    print("等待超时，可能按钮状态未改变或页面未完全加载。")
                    break  # 如果等待超时，退出循环
        except Exception as e:
            print(f"发生错误：{e}")

        finally:
            # 关闭浏览器
            # driver.quit()
            pass



if __name__ == '__main__':
    begin = datetime.datetime.now()
    ac = AutoClick(2)
    ac.generate()
    end = datetime.datetime.now()
    print(end-begin)


